package com.listeningframework.boot.autoconfigure.mail.senders;

import com.listeningframework.boot.autoconfigure.mail.domains.ListeningMailMessage;
import com.listeningframework.boot.exception.BusinessException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.activation.DataSource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Listening Mail Sender
 *
 * @author lixining
 * @version $Id: ListeningBaseMailSender.java, v 0.1 2015年11月4日 上午11:14:10 lixining Exp $
 */
public abstract class ListeningBaseMailSender {
    /**
     * 日志
     */
    protected static final Logger logger = LoggerFactory.getLogger(ListeningBaseMailSender.class);

    /**
     * Generate Mime mail message
     *
     * @param mailSender  Spring Mail Sender
     * @param message     要发送邮件内容封装
     * @return MimeMessage
     * @throws BusinessException  邮件内容构造异常
     */
    protected MimeMessage getMimeMailMessage(JavaMailSender mailSender, ListeningMailMessage message) throws BusinessException {
        try {
            List<String> mailToList = message.getSendTo();
            List<String> mailCcList = message.getSendCc();
            String sendFrom = message.getSendFrom();
            if (StringUtils.isBlank(sendFrom)) {
                throw new BusinessException("mail sender cant be empty");
            }
            if (CollectionUtils.isEmpty(mailToList)) {
                throw new BusinessException("mail receiver cant be empty");
            }
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "utf-8");
            helper.setFrom(message.getSendFrom());
            helper.setTo(mailToList.toArray(new String[mailToList.size()]));
            if (!CollectionUtils.isEmpty(mailCcList)) {
                helper.setCc(mailCcList.toArray(new String[mailCcList.size()]));
            }
            helper.setSubject(message.getTitle());
            helper.setText(message.getMessage(), true);

            Map<String, DataSource> attachmentMap = message.getAttachmentMap();
            if (attachmentMap == null || attachmentMap.isEmpty()) {
                return mimeMessage;
            }
            Set<Entry<String, DataSource>> attachSet = attachmentMap.entrySet();
            for (Entry<String, DataSource> attach : attachSet) {
                helper.addAttachment(attach.getKey(), attach.getValue());
            }
            return mimeMessage;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException("generate mimemailmessage fail", e);
        }
    }

    /**
     * Simple mail message
     *
     * @param message  邮件内容
     * @return SimpleMailMessage
     * @throws BusinessException  邮件构造异常
     */
    protected SimpleMailMessage getSimpleMailMessage(ListeningMailMessage message) throws BusinessException {
        try {
            SimpleMailMessage simpleMessage = new SimpleMailMessage();
            List<String> mailToList = message.getSendTo();
            String sendFrom = message.getSendFrom();
            if (StringUtils.isBlank(sendFrom)) {
                throw new BusinessException("mail sender cant be empty");
            }
            if (CollectionUtils.isEmpty(mailToList)) {
                throw new BusinessException("mail receiver cant be empty");
            }
            simpleMessage.setTo(mailToList.toArray(new String[mailToList.size()]));
            simpleMessage.setFrom(sendFrom);
            simpleMessage.setSentDate(new Date());
            simpleMessage.setSubject(message.getTitle());
            simpleMessage.setText(message.getMessage());
            return simpleMessage;
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            throw new BusinessException("generate simplemailmessage fail", e);
        }
    }

}
